﻿namespace PowerSong.UserInterface
    {
    using System.Collections.Generic;
    using System.Linq;
    using System.Windows;
    using Database = PowerSong.SongDatabase;

    /// <summary>
    /// Interaction logic for SelectItemsWindow.xaml
    /// </summary>
    public partial class SelectItemsWindow : Window
        {

        public Database.Style[] SelectedStyles { get; private set; }

        public Database.Song[] SelectedSongs { get; private set; }

        public class DataRow
            {
            public string Type { get; set; }
            public string Name { get; set; }
            public object Tag { get; set; }
            }

        public SelectItemsWindow(Database.Song[] availableSongs,
                                 Database.Style[] availableStyles)
            {
            InitializeComponent();
            
            // Add styles
            var rows = new List<DataRow>();
            var styles = availableStyles.OrderBy(style => style.Name);
            foreach (var style in styles)
                {
                rows.Add(new DataRow() { Type = "Style", Name = style.Name, Tag = style });
                }

            // Add songs
            var songs = availableSongs.OrderBy(song => song.Title);
            foreach (var song in songs)
                {
                rows.Add(new DataRow() { Type = "Song", Name = song.Title, Tag = song });
                }
            ItemsListView.ItemsSource = rows;

            }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
            {
            this.DialogResult = false;
            }

        private void OKButton_Click(object sender, RoutedEventArgs e)
            {

            // Set selected items
            var selectedStyles = new List<Database.Style>();
            var selectedSongs = new List<Database.Song>();
            foreach (DataRow item in ItemsListView.SelectedItems)
                {
                if (item.Tag is Database.Style) selectedStyles.Add((Database.Style)item.Tag);
                if (item.Tag is Database.Song) selectedSongs.Add((Database.Song)item.Tag);
                }
            this.SelectedStyles = selectedStyles.ToArray();
            this.SelectedSongs = selectedSongs.ToArray();

            // Close the window
            this.DialogResult = true;

            }

        private void SelectAllButton_Click(object sender, RoutedEventArgs e)
            {
            ItemsListView.SelectAll();
            }

        private void SelectNoneButton_Click(object sender, RoutedEventArgs e)
            {
            ItemsListView.UnselectAll();
            }

        }

    }
